<?php
  /**
   * iJPages
   *
   * The iJPages class 
   *
   * @copyright Copyright (c) 2011, iJBLOKS Progect
   */
    class iJPages {
        
        /**
         *
         * Class Constructuctor
         * @access public
         */
        public function __construct() {

        }
        public static function parseBlocks($header, $left, $right, $content, $footer) {
          $blocks = array();
          
          foreach($header as $value) {
              $block['id']       = substr($value, 6);
              $block['position'] = 'HEADER';
              $blocks[] = $block;
          }
          
          foreach($left as $value) {
              $block['id']       = substr($value, 6);
              $block['position'] = 'LEFT';
              $blocks[] = $block;
          }
          
          foreach($content as $value) {
              $block['id']       = substr($value, 6);
              $block['position'] = 'CONTENT';
              $blocks[] = $block;
          }
          
          foreach($right as $value) {
              $block['id']       = substr($value, 6);
              $block['position'] = 'RIGHT';
              $blocks[] = $block;
          }
          
          foreach($footer as $value) {
              $block['id']       = substr($value, 6);
              $block['position'] = 'FOOTER';
              $blocks[] = $block;
          }  
          
          return $blocks;
        }
        
        public static function createPreviewPage($header, $left, $right, $content, $footer, $pageStruct) {
            $pageStruct = cleanUpArray($pageStruct);
            $replay['state'] = 'success';
            $iJDataBase = iJFactory::singleton('iJDataBase');

            $QPages = $iJDataBase->query('SELECT
                                          id
                                        FROM :table_pages
                                        WHERE keyword = :pages_preview ');
            $QPages->bindTable(':table_pages', TABLE_PAGES);
            $QPages->bindValue(':pages_preview', 'pages_preview');
            $QPages->execute();
            if($QPages->next()) {
                
                $idPage = $QPages->value('id');
                $blocks = self::parseBlocks($header, $left, $right, $content, $footer);
                self::buildPage($blocks, $idPage, $pageStruct);
                
                
            } else {
                $replay['state'] = 'fail';
                return $replay; 
            }
            
            
           
            return $replay; 
        }
        
        public static function createPage($pageInfo, $header, $left, $right, $content, $footer, $pageStruct) {
          $iJDataBase  =  iJFactory::singleton('iJDataBase');
          $iJLanguages =  iJFactory::singleton('iJLanguages');
          $pageStruct1['x'] = 'y';
          $pageStruct = cleanUpArray($pageStruct);
          //TODO Data check
         // xDebug::save($pageInfo["keyword"]);
          foreach($pageInfo as $key => $value) {
            if(($key == 'keyword') || ($key == 'url') || ($key == 'admin') || ($key == 'idPage')) {
              $page[$key] = $value;
            }
            if(substr($key, 0, 5) == 'title') {
              $page[$key] = $value;
            }
          }
         
          /*Data check*/
          if(empty($page['keyword'])) {
            return iJMessages::ajaxDisplay('fail', 'fail');
          }

          if(empty($page['url'])) {
            return iJMessages::ajaxDisplay('fail', 'fail');
          }
               
          $iJDataBase->startTransaction();
          $QPage = $iJDataBase->query('INSERT INTO :table_pages
                                                    (
                                                        url,
                                                        keyword,
                                                        isAdminPage,
                                                        header,
                                                        cleft,
                                                        cright,
                                                        content,
                                                        footer
                                                    )
                                                    VALUES 
                                                    (
                                                        :url,
                                                        :keyword,
                                                        :isAdmin,
                                                        :header,
                                                        :left,
                                                        :right,
                                                        :content,
                                                        :footer
                                                        
                                                    )
                                      ON DUPLICATE KEY UPDATE 
                                        url         = :url,
                                        isAdminPage = :isAdmin,
                                        header      = :header,
                                        cleft       = :left,
                                        cright      = :right,
                                        content     = :content,
                                        footer      = :footer
                                      ');
          $QPage->bindTable(':table_pages',   TABLE_PAGES);
          $QPage->bindValue(':url',           $page['url']);
          $QPage->bindValue(':keyword',       $page['keyword']);
          $QPage->bindValue(':isAdmin',       (isset($page['admin']) && !empty($page['admin'])) ? 1 : 0);
          $QPage->bindValue(':header',        ($pageStruct['header'])     ? 'enable' : 'disable');
          $QPage->bindValue(':left',          ($pageStruct['left'])       ? 'enable' : 'disable');
          $QPage->bindValue(':right',         ($pageStruct['right'])      ? 'enable' : 'disable');
          $QPage->bindValue(':content',       ($pageStruct['content'])    ? 'enable' : 'disable');
          $QPage->bindValue(':footer',        ($pageStruct['footer'])     ? 'enable' : 'disable');

          $QPage->execute();
          if(!$iJDataBase->isError()) {
            $newPage = true;
            if(empty($page['idPage'])) {
              $idPage = $iJDataBase->getLastInsertId();
            } else {
              $idPage = $page['idPage'];
              $newPage = false;
            }
            $languages = $iJLanguages->getLanguages();
            foreach($languages as $lang) {
                if(isset($page['title_' . $lang['code']])) {
                    $definition = $page['title_' . $lang['code']];
                } else {
                    //TODO as tocken
                    $definition = 'unset';
                }
                $iJLanguages->addDefinition(TABLE_PAGES, $idPage, $lang['code'], $definition);
                
            }
            if(!$iJDataBase->isError()) {
                $blocks = self::parseBlocks($header, $left, $right, $content, $footer);
                self::buildPage($blocks, $idPage);
                if(!$iJDataBase->isError()) {
                  $iJDataBase->commitTransaction();
                  if($newPage) {
                    return iJMessages::ajaxDisplay('success', 'created');
                  } else {
                    return iJMessages::ajaxDisplay('success', 'applayed');
                  }
                  
                } else {
                  return iJMessages::ajaxDisplay('fail', 'fail');;
                  $iJDataBase->rollbackTransaction();
                }
                
            } else {
                return iJMessages::ajaxDisplay('fail', 'fail');
                $iJDataBase->rollbackTransaction();
            }
            
          }
        }
        
        
        public static function createPageGroup($groupInfo) {
          $iJDataBase  =  iJFactory::singleton('iJDataBase');
          $iJLanguages =  iJFactory::singleton('iJLanguages');
          $iJDataBase->startTransaction();
          $QPage = $iJDataBase->query('INSERT INTO :table_pages 
                                                    (
                                                        url,
                                                        keyword,
                                                        isAdminPage
                                                    )
                                                    VALUES 
                                                    (
                                                        :url,
                                                        :keyword,
                                                        :isAdmin
                                                        
                                                    )
                                      ON DUPLICATE KEY UPDATE 
                                        url         = :url,
                                        isAdminPage = :isAdmin
                                      ');
          $QPage->bindTable(':table_pages',   TABLE_PAGES);
          $QPage->bindValue(':url',           $page['url']);
          $QPage->bindValue(':keyword',       $page['keyword']);
          $QPage->bindValue(':isAdmin',       (isset($page['admin']) && !empty($page['admin'])) ? 1 : 0);
          $QPage->execute();
          if(!$iJDataBase->isError()) {
            $newPage = true;
            if(empty($page['idPage'])) {
              $idPage = $iJDataBase->getLastInsertId();
            } else {
              $idPage = $page['idPage'];
              $newPage = false;
            }
            $languages = $iJLanguages->getLanguages();
            foreach($languages as $lang) {
                if(isset($page['title_' . $lang['code']])) {
                    $definition = $page['title_' . $lang['code']];
                } else {
                    //TODO as tocken
                    $definition = 'unset';
                }
                $iJLanguages->addDefinition(TABLE_PAGES, $idPage, $lang['code'], $definition);
                
            }
            if(!$iJDataBase->isError()) {
                $blocks = self::parseBlocks($header, $left, $right, $content, $footer);
                self::buildPage($blocks, $idPage);
                if(!$iJDataBase->isError()) {
                  $iJDataBase->commitTransaction();
                  if($newPage) {
                    return iJMessages::ajaxDisplay('success', 'created');
                  } else {
                    return iJMessages::ajaxDisplay('success', 'applayed');
                  }
                  
                } else {
                  return iJMessages::ajaxDisplay('fail', 'fail');;
                  $iJDataBase->rollbackTransaction();
                }
                
            } else {
                return iJMessages::ajaxDisplay('fail', 'fail');
                $iJDataBase->rollbackTransaction();
            }
            
          }
        }
        
        
                
        public static function buildPage($blocks, $idPage, $pageStruct = null) {
          $iJDataBase = iJFactory::singleton('iJDataBase');
          if($pageStruct != null) {
            $QPage = $iJDataBase->query('UPDATE  :table_pages
                                          SET
                                            header      = :header,
                                            cleft       = :left,
                                            cright      = :right,
                                            content     = :content,
                                            footer      = :footer
                                          WHERE id = :id
                                        ');
            $QPage->bindTable(':table_pages',   TABLE_PAGES);
            $QPage->bindValue(':id',           $idPage);
            $QPage->bindValue(':header',        ($pageStruct['header'])     ? 'enable' : 'disable');
            $QPage->bindValue(':left',          ($pageStruct['left'])       ? 'enable' : 'disable');
            $QPage->bindValue(':right',         ($pageStruct['right'])      ? 'enable' : 'disable');
            $QPage->bindValue(':content',       ($pageStruct['content'])    ? 'enable' : 'disable');
            $QPage->bindValue(':footer',        ($pageStruct['footer'])     ? 'enable' : 'disable');
            $QPage->execute();
          }
          
          $QPages = $iJDataBase->query('DELETE FROM :table_blocks_to_pages
                                           WHERE idPage = :idPage ');
          $QPages->bindTable(':table_blocks_to_pages', TABLE_BLOCKS_TO_PAGES);
          $QPages->bindValue(':idPage', $idPage, 'int'); 
          $QPages->execute();
          // xDebug::save($blocks);
          if(!empty($blocks)) {
              
            $QPages = $iJDataBase->query('INSERT INTO :table_blocks_to_pages
                                                (
                                                   idPage,
                                                   idBlock,
                                                   place
                                                 )
                                                 VALUES');
            $QPages->bindTable(':table_blocks_to_pages', TABLE_BLOCKS_TO_PAGES);
            $term = '';
            foreach ($blocks as $block) {
                $QPages->appendQuery($term . '(:idPage, :idBlock, :place)');
                $QPages->bindValue(':idPage',  $idPage,         'int'); 
                $QPages->bindValue(':idBlock', $block['id'],    'int'); 
                $QPages->bindValue(':place', $block['position']); 
                $term = ',';
            }  
            $QPages->execute();
          }
             
            
        }
        
        
        public function getPagesList($page, $search, $limit = '') {
          $iJDataBase =  iJFactory::singleton('iJDataBase');
          $QPages = $iJDataBase->query('SELECT 
                                         P.id, 
                                         P.url, 
                                         def.value as title,
                                         P.isAdminPage, 
                                         P.keyword    
                                       FROM :table_pages AS P
                                            :lang_join');
          $QPages->bindTable(':table_pages', TABLE_PAGES);
          $QPages->bindLaguageDefinitions(':lang_join', TABLE_PAGES, 'P');
          
          
          if(!empty($search)) {
            $QPages->appendQuery('AND((def.value like :search)  OR
                                      (P.url like :search)       OR 
                                      (P.keyword like :search))');
            $QPages->bindValue(':search', '%' . $search . '%');
          }
          
          $QPages->appendQuery(':limit');
          $QPages->bindTable(':limit', $QPages->addLimit($page, $limit));
          $QPages->execute();
          
          $pages = array();
          while ($QPages->next()) {
            $idPage = $QPages->value('id');
            $pages[$idPage]['keyword']     = $QPages->value('keyword');
            $pages[$idPage]['url']         = BASE_URL . $QPages->value('url');
            $pages[$idPage]['title']       = $QPages->value('title');
            $pages[$idPage]['isAdminPage'] = $QPages->value('isAdminPage');
            $pages[$idPage]['edit']        = iJHrefLink::linkToLocalPage('page_edit',   iJHrefLink::Icon('edit',  '16x16'), array('key'   => $QPages->value('keyword')));
            $pages[$idPage]['editlink']    = iJHrefLink::linkToLocalPage('page_edit')   . '?key=' . $QPages->value('keyword');
            $pages[$idPage]['trash']       = iJHrefLink::linkToLocalPage('admin_pages') . '?del=' . $idPage;
          }
          return array($pages, $QPages);
        }
         
         
       public function getPageByKeyword($keyword) {
         $iJDataBase =  iJFactory::singleton('iJDataBase');
         $iJLanguages =  iJFactory::singleton('iJLanguages');
         $QPages = $iJDataBase->query('SELECT 
                                         P.id, 
                                         P.url, 
                                         def.value as title,
                                         P.isAdminPage, 
                                         P.keyword,
                                         P.header,
                                         P.cleft,
                                         P.cright,
                                         P.content,
                                         P.footer  
                                       FROM :table_pages AS P
                                            :lang_join');
         $QPages->bindTable(':table_pages', TABLE_PAGES);
         $QPages->bindLaguageDefinitions(':lang_join', TABLE_PAGES, 'P');
          
         $QPages->appendQuery('AND (P.keyword like :key)');
         $QPages->bindValue(':key',  $keyword);
         $QPages->execute();
         
         $page = array();
         if ($QPages->next()) {
           $idPage = $QPages->value('id');
           $page['id']          = $idPage;
           $page['keyword']     = $QPages->value('keyword');
           $page['url']         = $QPages->value('url');
           $page['header']      = $QPages->value('header');
           $page['cleft']       = $QPages->value('cleft');
           $page['cright']      = $QPages->value('cright');
           $page['content']     = $QPages->value('content');
           $page['footer']      = $QPages->value('footer');
           $page['isAdminPage'] = $QPages->value('isAdminPage');
         }
         if(isset($page['id'])) {
           $languages = $iJLanguages->getLanguages();
           foreach($languages as $lang) {
             $page['title'][$lang['code']] = $iJLanguages->getDefinition(TABLE_PAGES, $page['id'], $lang['code']);  
           }
         }
         
         return $page;
       }
       
        public function getPageBlocksById($id) {
          $iJDataBase =  iJFactory::singleton('iJDataBase');
          $iJLanguages =  iJFactory::singleton('iJLanguages');
          $QBlocks   = $iJDataBase->query('SELECT
                                            idBlock,
                                            place
                                          FROM :table_blocks_to_pages
                                          WHERE idPage = :id');
          $QBlocks->bindTable(':table_blocks_to_pages', TABLE_BLOCKS_TO_PAGES);
          $QBlocks->bindValue(':id',  $id);
          $QBlocks->execute();
         // spr($QBlocks);
          $blocks = array();
          while($QBlocks->next()) {
            $blocks[$QBlocks->value('place')][$QBlocks->value('idBlock')]['id']    = $QBlocks->value('idBlock');
            $blocks[$QBlocks->value('place')][$QBlocks->value('idBlock')]['title'] = $iJLanguages->getDefinition(TABLE_BLOCKS, $QBlocks->value('idBlock'));
          }
          
          return $blocks;
        }
        
        public function delPageById($id) {
          $iJDataBase =  iJFactory::singleton('iJDataBase');
          $iJLanguages =  iJFactory::singleton('iJLanguages');
          $iJDataBase->startTransaction();
          $QBlocks   = $iJDataBase->query('DELETE
                                            FROM :table_pages
                                            WHERE id = :id');
                                            
          $QBlocks->bindTable(':table_pages', TABLE_PAGES);
          $QBlocks->bindValue(':id',  $id);
          $QBlocks->execute(); 
          if(!$iJDataBase->isError()) {
            $iJLanguages->removeDefinitions(TABLE_PAGES, $id);
             if(!$iJDataBase->isError()) {
                  $iJDataBase->commitTransaction();
                  iJMessages::display('success', 'page_delete');
              } else {
                iJMessages::display('fail', 'fail');
                $iJDataBase->rollbackTransaction();
              }
              
          } else {
            iJMessages::display('fail', 'fail');
            $iJDataBase->rollbackTransaction();
          }
        } 
         
    }
?>